﻿using System;
using System.Reflection;
using System.Windows.Input;

namespace WinRTControl.Fixed
{
    public  class RelayCommand<T> : ICommand
    {
        private readonly Action<T> _execute;
        private readonly Func<T, bool> _canExecute;

        public RelayCommand(Action<T> execute)
            : this(execute, null)
        {

        }

        public RelayCommand(Action<T> execute, Func<T, bool> canExecute)
        {
            if (execute == null)
            {
                throw new ArgumentNullException("execute");
            }
            _execute = execute;
            if (_canExecute != null)
            {
                _canExecute = canExecute;
            }
        }

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
            {
                return true;
            }
            if (parameter == null && typeof(T).GetTypeInfo().IsValueType)
            {
                return _canExecute(default(T));
            }
            else
            {
                return _canExecute((T)parameter);
            }
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            if (CanExecute(parameter) && _execute != null)
            {
                if (typeof(T).GetTypeInfo().IsValueType)
                {
                    _execute(default(T));
                }
                else
                {
                    _execute((T)parameter);
                }
            }
        }
    }
}
